import { v4 as uuid } from 'uuid'
import { StdParagraphV2 } from './paragraph'
import tinymce from 'tinymce/tinymce'

export class StdFormulaV2 {
  constructor(node) {
    this.node = node
    this.img = node.querySelector('img')
    this.formulaData = null
  }
  get data() {
    try {
      const variables = [...this.node?.querySelectorAll('.variables > p')]
      this.formulaData = {
        url: tinymce.activeEditor.getDoc()?.querySelector(`[data-id="${this.node?.dataset?.id}"] img`)?.src,
        dataId: this.node?.dataset?.id,
        width: this.img?.width,
        height: this.img?.height,
        unit: this.node?.dataset?.unit,
        formulaNumber: this.node?.dataset?.formulaNumber,
        latex: this.node?.dataset?.latex || '',
        variableList: variables.filter((node) => node?.nodeName === 'P').map((node) => new StdParagraphV2(node).data)
      }
    } catch (error) {
      console.error('公式解析出错')
    }

    return this.formulaData
  }
}

export class StdFormulaDataV2 {
  constructor({ url, dataId, width, height, unit, formulaNumber, latex = '', variableList = [] }) {
    // 图片的链接
    this.url = url
    // 数据唯一标识
    this.dataId = dataId || uuid()
    // 宽-单位像素
    this.width = width
    // 高-单位像素
    this.height = height
    // 公式单位
    this.unit = unit
    // 公式编号
    this.formulaNumber = formulaNumber
    // 公式内容
    this.latex = latex
    // 变量数组
    this.variableList = variableList
  }
}
